package com.lc1993929.myhdfs.server;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

/**
 * Created by LiuChang on 2017/9/1/001.
 */
public class DataNodeHandler implements Runnable {
    private Socket sc;

    @Override
    public void run() {
        try {
            InputStream fromClientIn = sc.getInputStream();

            //接收客户端存block的请求
            byte[] b = new byte[22];
            fromClientIn.read(b);

            String request = new String(b);
            System.out.println(request);

            String[] split = request.split(":");
            String blkId = split[1];

            //接收客户端的文件块数据流，存入本地的磁盘目录，取名为blockid
            FileOutputStream fout = new FileOutputStream("f:/hdfs/" + blkId);
            byte[] buf = new byte[4096];
            int len = 0;
            while ((len = fromClientIn.read(buf)) != -1) {
                fout.write(buf, 0, len);
            }

            fout.close();
            fromClientIn.close();
            sc.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public DataNodeHandler(Socket sc) {
        this.sc = sc;
    }
}
